import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import 'package:flutter_wisave/widgets/AppColors.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:flutter_wisave/widgets/indicator.dart';
import '../../widgets/LineChartSampleZhe1.dart';
import '../../Common/weekTime.dart';

class WorkViewDetail extends StatefulWidget {
  List<double> spots;
  int typeValue; // 0预热 3均热

  WorkViewDetail({
    super.key,
    this.spots = const [20, 40, 90, 30, 80, 20],
    required this.typeValue,
  });

  @override
  _WorkViewDetailState createState() => _WorkViewDetailState();
}

class _WorkViewDetailState extends State<WorkViewDetail>
    with TickerProviderStateMixin {
  late TabController _tabController;
  String dateNow =
      "${DateTime.now().year}.${DateTime.now().month.toString().padLeft(2, '0')}.${DateTime.now().day.toString().padLeft(2, '0')}"; // 默认今天年月日
  late List<String> xTitle = []; //'1', '2', '3', '4', '5'];
  List<dynamic> listData = [];
  int typeTime = 0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _fetchSteelOutHourData(dateNow);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<List<dynamic>> _fetchSteelOutHourData(String date) async {
    print(date);
    final NetworkService _networkService = NetworkService();
    try {
      final response = await _networkService.get(
          '/plcTimer/procedurevalue2day/dayInfo',
          queryParameters: {'startDate': date, 'companyId': '103'});
      if (response.statusCode == 200) {
        setState(() {
          listData = (response.data['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList()
              .fold<List<Map<String, dynamic>>>([], (acc, item) {
            if (!acc
                .any((element) => element['timeStamp'] == item['timeStamp'])) {
              acc.add(item);
            }
            return acc;
          })
            ..sort((a, b) => DateTime.parse(a['timeStamp'])
                .compareTo(DateTime.parse(b['timeStamp'])));

          xTitle = listData.map((item) {
            DateTime date = DateTime.parse(item['timeStamp']);
            return '${date.month}.${date.day}';
          }).toList();
        });
        return listData;
      } else {
        print('炉温趋势: ${response.statusCode}');
        return [];
      }
    } catch (e) {
      print('Error in _fetchSteelOutHourData: $e');
      return [];
    }
  }

  @override
  Widget build(BuildContext context) {
    // 设置为横屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeRight,
      DeviceOrientation.landscapeLeft,
    ]);

    return WillPopScope(
      onWillPop: () async {
        // 页面返回时，调回竖屏
        SystemChrome.setPreferredOrientations([
          DeviceOrientation.portraitUp,
          DeviceOrientation.portraitDown,
        ]);
        return true;
      },
      child: Scaffold(
        backgroundColor: AppColors.backgroundColor,
        appBar: AppBar(
          title: SizedBox(
            child: Row(
              children: [
                Text(
                  '炉温趋势',
                  style: TextStyle(color: AppColors.textPrimary),
                ),
                SizedBox(
                  width: 20,
                ),
                if (typeTime != 1)
                  Text(dateNow,
                      style: TextStyle(
                          color: const Color(0xFFFCAA3F), fontSize: 16)),
                if (typeTime == 1)
                  weekTime(
                    onDateChanged: (DateTime) {},
                  ),
                Expanded(
                  child: SizedBox(),
                ),
                Image.asset(
                  'assets/images/centre/icon_date.png',
                  fit: BoxFit.cover,
                ),
                SizedBox(width: 5),
                if (typeTime != 1)
                  TDButton(
                    text: '请选择日期',
                    textStyle:
                        TextStyle(fontSize: 14, color: AppColors.textSecondary),
                    size: TDButtonSize.medium,
                    type: TDButtonType.outline,
                    shape: TDButtonShape.rectangle,
                    theme: TDButtonTheme.defaultTheme,
                    style: TDButtonStyle(
                      backgroundColor: AppColors.cardColor,
                    ),
                    onTap: () {
                      TDPicker.showDatePicker(
                        context,
                        title: '选择时间',
                        pickerHeight: 120,
                        onConfirm: (selected) {
                          setState(() {
                            dateNow =
                                '${selected['year'].toString().padLeft(4, '0')}-${selected['month'].toString().padLeft(2, '0')}-${selected['day'].toString().padLeft(2, '0')}';
                            _fetchSteelOutHourData(dateNow);
                          });
                          Navigator.of(context).pop();
                        },
                        dateStart: [DateTime.now().year - 10, 01, 01],
                        dateEnd: [
                          DateTime.now().year,
                          DateTime.now().month,
                          DateTime.now().day
                        ],
                        initialDate: [
                          DateTime.now().year,
                          DateTime.now().month,
                          DateTime.now().day
                        ],
                      );
                    },
                  )
              ],
            ),
          ),
          backgroundColor: Colors.transparent,
          flexibleSpace: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/home/home_topbg.png'),
                fit: BoxFit.cover,
              ),
            ),
          ),
        ),
        body: SingleChildScrollView(
          child: Column(children: [
            Padding(
              padding: EdgeInsets.all(16),
              child: Container(
                width: double.infinity,
                // height: 100,
                padding: EdgeInsets.all(16.0),
                decoration: BoxDecoration(
                  color: AppColors.cardColor,
                  borderRadius: BorderRadius.circular(8.0),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.2),
                      blurRadius: 6.0,
                    ),
                  ],
                ),
                child: Column(
                  children: [
                    // 第一排文字
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Text('上炉温：1222（℃）',
                            style: TextStyle(
                                fontSize: 16, color: AppColors.textPrimary)),
                        SizedBox(
                          width: 20,
                        ),
                        Text('最大值：1223（℃）',
                            style: TextStyle(
                                fontSize: 16, color: AppColors.textPrimary)),
                        SizedBox(
                          width: 20,
                        ),
                        Text('最小值：1220（℃）',
                            style: TextStyle(
                                fontSize: 16, color: AppColors.textPrimary)),
                      ],
                    ),
                    SizedBox(height: 10), // 添加间距
                    // 第二排文字
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Text('下炉温：1222（℃）',
                            style: TextStyle(
                                fontSize: 16, color: AppColors.textPrimary)),
                        SizedBox(
                          width: 20,
                        ),
                        Text('最大值：1223（℃）',
                            style: TextStyle(
                                fontSize: 16, color: AppColors.textPrimary)),
                        SizedBox(
                          width: 20,
                        ),
                        Text('最小值：1220（℃）',
                            style: TextStyle(
                                fontSize: 16, color: AppColors.textPrimary)),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.only(left: 16, right: 16, bottom: 16),
              child: Container(
                  width: double.infinity,
                  // height: 100,
                  padding: EdgeInsets.all(5.0),
                  decoration: BoxDecoration(
                    color: AppColors.cardColor,
                    borderRadius: BorderRadius.circular(8.0),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.2),
                        blurRadius: 6.0,
                      ),
                    ],
                  ),
                  child: Column(
                    children: [
                      Row(children: [
                        TDTabBar(
                          // width: 300,
                          tabs: const [
                            TDTab(
                              text: '日',
                            ),
                            TDTab(
                              text: '周',
                            ),
                            TDTab(
                              text: '年',
                            ),
                          ],
                          controller: _tabController,
                          labelColor: Color(0xFF2AB6F7),
                          unselectedLabelColor: AppColors.textSecondary,
                          indicatorColor: Color(0xFF2AB6F7),
                          dividerColor: Colors.transparent,
                          backgroundColor: Colors.transparent,
                          showIndicator: true,
                          width: 300,
                          onTap: (index) {
                            setState(() {
                              typeTime = index;
                              print('===========$typeTime');
                              String d = dateNow.replaceAll(
                                  '.', '-'); // 将日期格式从“.”替换为“-”
                              switch (index) {
                                case 0:
                                  d = d.substring(0, 10); // 日
                                  break;
                                case 1:
                                  d = d.substring(0, 7); // 周
                                  break;
                                case 2:
                                  d = d.substring(0, 4); // 年
                                  break;
                              }
                              _fetchSteelOutHourData(d);
                            });
                          },
                        ),
                        Text(
                          '（℃）',
                          style: TextStyle(color: AppColors.textPrimary),
                        )
                      ]),
                      SizedBox(
                        height: 10,
                      ),
                      Row(
                        children: [
                          SizedBox(
                            width: 15,
                          ),
                          Indicator(
                            color: Color(0xFF2AB6F7),
                            text: '上炉温',
                            isSquare: true,
                            size: 12,
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          Indicator(
                            color: Color(0xFFFCAA3F),
                            text: '下炉温',
                            isSquare: true,
                          ),
                          Expanded(child: Container()),
                          Text(
                            widget.typeValue == 0
                                ? '预热段'
                                : (widget.typeValue == 1 ? '加一段' : '加二段'),
                            style: TextStyle(
                                fontSize: 13,
                                fontWeight: FontWeight.normal,
                                color: AppColors.textPrimary),
                          ),
                          SizedBox(
                            width: 50,
                          ),
                        ],
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      LineChartSampleZhe1(
                        xTitle: xTitle,
                        typeValue: widget.typeValue,
                        listData: listData,
                      ),
                    ],
                  )),
            ),
          ]),
        ),
      ),
    );
  }
}
